package io.yuncheng.common.utils;

import com.alibaba.fastjson.JSON;
import io.yuncheng.modules.job.entity.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

@Slf4j
public class HttpClientUtils {
    public static final String GET = "GET";
    public static final String POST = "POST";
    public static final String URL = "http://10.208.203.84:1098/agent";

    public static void main(String[] args) {
        String url = "http://49.232.45.79:8280/renren-admin/sys/dept/list-page";
        String post = http("POST", url, "");
        System.out.println(post);
    }

    public static String postHttp(String url, String data) {
        log.info("url: {}, data : {} ",url,data);
        String result = http(POST, url, data);
        log.info("result: {} ",url,result);
        return result;
    }

    public static ResponseEntity postHttpResult(String url, String data) {
        return JSON.parseObject(http(POST, url, data), ResponseEntity.class) ;
    }

    public static String getHttp(String url, String data) {
        return http(GET, url, data);
    }

    public static String http(String type, String url, String data) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json;");
        RequestBody body = RequestBody.create(mediaType, data);
        Request request = new Request.Builder()
                .url(url)
                .method(type, body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
